package com.cgy.utils.spider.resolver;

import java.util.List;
import java.util.Map;

import com.cgy.utils.spider.callback.AbstractCallBack;
import com.cgy.utils.spider.element.AbstractElement;
import com.cgy.utils.spider.pojo.Element;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;
import us.codecraft.webmagic.Page;

/**
 * webmgic解析器
 * @author CH
 *
 */
@Slf4j
public class WebMagicResolver extends AbstractResolver{

	@Override
	public Map<String, Object> analysis(Object page, AbstractCallBack callBack) {
		Map<String, Object> result = Maps.newHashMap();
		//获取当前页
		Page page1 = (Page) page;
		//获取解析数据
		AbstractElement element2 = super.getElement();
		List<Element> lElements = element2.getLElements();
		for (Element element : lElements) {
			if(element2.isDebugger()) {
				log.debug("name: {}-value: {}", element.getName(), page1.getHtml().xpath(element.getXpath()));
			}
			result.put(element.getName(), page1.getHtml().xpath(element.getXpath()));
		}
		if(null != element2.getLatch()) {
			element2.getLatch().latch(result);
		}
		if(null != callBack) {
			callBack.callback(result);
		}
		element2.setResult(result);
		return result;
	}

	@Override
	public void before() {
		
	}

	@Override
	public void after() {
		
	}

}
